package com.grq.mis.service;


import com.grq.mis.dao.ItemDao;
import com.grq.mis.dao.OrderDao;
import com.grq.mis.entity.Item;
import com.grq.mis.entity.Order;
import com.grq.mis.exception.BusinessException;
import com.grq.mis.exception.ResultEnum;
import com.grq.mis.model.sys.Me;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Transactional
@Service
public class OrderService extends BaseService<Order>{

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ItemDao itemDao;

    public void buy(Long itemId, Integer count, String name, String phone, String address, Me me) {

        Item item = itemDao.single(itemId);
        if (item == null){
            throw new BusinessException(ResultEnum.ERROR,"商品信息不存在");
        }
        if (item.getLeftCount() < count){
            throw new BusinessException(ResultEnum.ERROR,"库存不足");
        }

        Order order = new Order();
        order.setCreateTime(new Date());
        order.setItemMoney(item.getPrice());
        order.setItemCount(count);
        order.setPayMoney(item.getPrice() * count);
        order.setUserId(me.getId());
        order.setName(name);
        order.setPhone(phone);
        order.setAddress(address);
        order.setItemId(item.getId());
        order.setTitle(item.getTitle());
        order.setMainImg1Url(item.getMainImg1Url());
        order.setCategoryId(item.getCategoryId());
        order.setCategoryName(item.getCategoryName());
        order.setDepartmentId(me.getDepartmentId());
        order.setDepartmentName(me.getDepartmentName());
        orderDao.insert(order);

        item.setLeftCount(item.getLeftCount() - count);
        itemDao.updateById(item);

    }

    public void deleteOrder(Long id, Me me) {

        Order order = orderDao.single(id);
        if (order == null) {
            throw new BusinessException(ResultEnum.ERROR,"订单不存在");
        }

        if (!order.getDepartmentId().equals(me.getDepartmentId())){
            if (me.getId() != 1L){
                throw new BusinessException(ResultEnum.ERROR,"无权修改其他商户的订单信息");
            }
        }

        orderDao.deleteById(id);

    }

}
